//
//  RichTextEditViewController.m
//  RichTextEditDemo
//
//  Created by aron on 2017/7/19.
//  Copyright © 2017年 aron. All rights reserved.
//

#import "RichTextEditViewController.h"
#import <Masonry.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UtilMacro.h"
#import "MMFileUploadUtil.h"
#import "MMRichContentUtil.h"

#import "MMRichTextConfig.h"
#import "MMDraftUtil.h"

#import "MMRichTitleModel.h"
#import "MMRichTextModel.h"
#import "MMRichImageModel.h"
#import "MMDraftModel.h"

#import "MMRichTitleCell.h"
#import "MMRichTextCell.h"
#import "MMRichImageCell.h"
#import "MMRichEditAccessoryView.h"


#define contentInputAccessoryViewHeight     convertLength(50)
#define bottomOffsetHeight                  convertLength(49)


@interface RichTextEditViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, RichTextEditArcDelegate, MMRichEditAccessoryViewDelegate>
{
    BOOL _isRefreshShow;
    
    CYCategrayModel *_selBigCateModel;
    CYCategrayModel *_selSmallCateModel;

    UIButton *_labelBtn;//需要选的分类按钮
    BOOL _haveFaBu;
}

@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) UIView *refreshBackView;
@property (nonatomic, strong) UILabel *refreshTipLabel;

@property (nonatomic, strong) MMRichEditAccessoryView *contentInputAccessoryView;
@property (nonatomic, strong) UIView *editToolbar;

@property (nonatomic, strong) MMRichTitleModel* titleModel;
@property (nonatomic, strong) NSMutableArray* datas;
@property (nonatomic, strong) NSIndexPath* activeIndexPath;

@property (nonatomic, copy) NSString* tid;///<论坛ID
@property (nonatomic, strong) MMDraftModel* draft;

@property (nonatomic, assign) BOOL shouldShowAccessoryView;
@property (nonatomic, assign) BOOL isOnUploading;

@property (nonatomic, strong) UIView *bottomView;
@property (strong, nonatomic) HXPhotoManager *manager;

@property (nonatomic, strong) NSMutableArray* categaryArr;
@property (nonatomic, strong) NSDictionary* resultDic;
@property (nonatomic, strong) CYProjectModel *detailModel;

@end

@implementation RichTextEditViewController

- (instancetype)initWithTid:(NSString*)tid {
    self = [super init];
    if (self) {
        _tid = tid;
    }
    return self;
}

- (instancetype)initWithDraft:(MMDraftModel*)draft {
    self = [super init];
    if (self) {
        _tid = draft.tid;
        _draft = draft;
    }
    return self;
}

- (ResourceFrom)from{
    if (!_from) {
        _from = ResourceFrom_FaBu;
    }
    return _from;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"发布文章";
    [self rightBarItemWithTitle:@"发布"];
    [self getAllCategary];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 40, 40);
    [button setImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
//        make.top.equalTo(self.view).with.mas_equalTo(0);
//        make.left.equalTo(self.view).with.mas_equalTo(0);
//        make.right.equalTo(self.view).with.mas_equalTo(0);
//        make.height.mas_equalTo(300);
    }];
    [self.view addSubview:self.refreshBackView];

    
    // register cell
    [self.tableView registerClass:MMRichTitleCell.class forCellReuseIdentifier:NSStringFromClass(MMRichTitleCell.class)];
    [self.tableView registerClass:MMRichTextCell.class forCellReuseIdentifier:NSStringFromClass(MMRichTextCell.class)];
    [self.tableView registerClass:MMRichImageCell.class forCellReuseIdentifier:NSStringFromClass(MMRichImageCell.class)];
    
    // Datas
    if (_draft) {
        if ((MMRichTitleModel*)_draft.titleModel) {
            _titleModel = (MMRichTitleModel*)_draft.titleModel;
        } else {
            _titleModel = [MMRichTitleModel new];
        }
        _datas = [NSMutableArray array];
        if (_draft.contentModels) {
            [_datas addObjectsFromArray:_draft.contentModels];
        } else {
            [_datas addObject:[MMRichTextModel new]];
        }
    } else {
        _titleModel = [MMRichTitleModel new];
        _datas = [NSMutableArray array];
        [_datas addObject:[MMRichTextModel new]];
    }
    
    // AccessoryView
    [self.view addSubview:self.contentInputAccessoryView];
    [self.contentInputAccessoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(contentInputAccessoryViewHeight);
        make.height.equalTo(@(contentInputAccessoryViewHeight));
        make.left.right.equalTo(self.view);
    }];
    
    // Notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    if (self.articleId) {
        [self getDetail];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        
    }
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = NO;

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [UITableView new];
        _tableView.backgroundColor = BackGroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //        tableView.estimatedRowHeight = 200;
        //        tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTableViewTap)]];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, bottomOffsetHeight, 0);
        _tableView.tableFooterView = self.bottomView;
    }
    return _tableView;
}

- (MMRichEditAccessoryView *)contentInputAccessoryView {
    if (!_contentInputAccessoryView) {
        _contentInputAccessoryView = [[MMRichEditAccessoryView alloc] init];
        _contentInputAccessoryView.backgroundColor = [UIColor whiteColor];
        _contentInputAccessoryView.delegate = self;
        
//        UIImageView* footerBar = [UIImageView new];
//        footerBar.image = [UIImage imageNamed:@"zpgl_fb_wztp"];
//        [_contentInputAccessoryView addSubview:footerBar];
//        [footerBar mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.equalTo(self->_contentInputAccessoryView);
//            make.bottom.equalTo(self->_contentInputAccessoryView.mas_top);
//            make.height.equalTo(@(40));
//        }];
    }
    return _contentInputAccessoryView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    NSLog(@"===dealloc===");
}


#pragma mark - ......::::::: private :::::::......

- (void)handleSelectPics {
    
    // 判读已有的图片数
    if ([MMRichContentUtil imageCountFromRichContents:_datas] >= MMEditConfig.maxImageCount) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"图片上传已满" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [self hx_presentSelectPhotoControllerWithManager:self.manager didDone:^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL isOriginal, UIViewController *viewController, HXPhotoManager *manager) {
        [UINavigationBar appearance].translucent = NO;
        NSLog(@"block - all - %@",allList);
        NSLog(@"block - photo - %@",photoList);
        NSLog(@"block - video - %@",videoList);
        if (photoList.count > 0) {
            for (int i = 0; i < photoList.count; i++) {
                HXPhotoModel *model = photoList[i];
                [model requestPreviewImageWithSize:PHImageManagerMaximumSize startRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
                    // 如果照片在iCloud上会去下载,此回调代表开始下载iCloud上的照片
                    // 如果照片在本地存在此回调则不会走
                } progressHandler:^(double progress, HXPhotoModel *model) {
                    // iCloud下载进度
                    // 如果为网络图片,则是网络图片的下载进度
                } success:^(UIImage *image, HXPhotoModel *model, NSDictionary *info) {
                    // 获取成功
                    [self handleInsertImage:image];
                } failed:^(NSDictionary *info, HXPhotoModel *model) {
                    // 获取失败
                }];
            }
        }
    } cancel:^(UIViewController *viewController, HXPhotoManager *manager) {
        NSLog(@"block - 取消了");
        [UINavigationBar appearance].translucent = NO;
    }];
}


- (void)handleInsertImage:(UIImage*)image {
    
    if (!_activeIndexPath) {
        _activeIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    }
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:_activeIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 处理文本节点
        // 根据光标拆分文本节点
        BOOL isPre = NO;
        BOOL isPost = NO;
        NSArray* splitedTexts = [((MMRichTextCell*)cell) splitedTextArrWithPreFlag:&isPre postFlag:&isPost];
        
        // 前面优先级更高，需要调整优先级，调整if语句的位置即可
        if (isPre) {
            // 前面添加图片，光标停留在当前位置
            [self addImageNodeAtIndexPath:_activeIndexPath image:image];
            [self postHandleAddImageNode:_activeIndexPath];
        } else if (isPost) {
            // 后面添加图片，光标移动到下一行
            NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:_activeIndexPath.row + 1 inSection:_activeIndexPath.section];
            [self addImageNodeAtIndexPath:nextIndexPath image:image];
            [self postHandleAddImageNode:nextIndexPath];
        } else {
            // 替换当前节点，添加Text/image/Text，光标移动到图片节点上
            NSInteger tmpActiveIndexRow = _activeIndexPath.row;
            NSInteger tmpActiveIndexSection = _activeIndexPath.section;
            [self deleteItemAtIndexPath:_activeIndexPath shouldPositionPrevious:NO];
            if (splitedTexts.count == 2) {
                // 第一段文字
                [self addTextNodeAtIndexPath:_activeIndexPath textContent:[splitedTexts.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                // 图片
                [self addImageNodeAtIndexPath:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection] image:image];
                // 第二段文字
                [self addTextNodeAtIndexPath:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 2 inSection:_activeIndexPath.section] textContent:[splitedTexts.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                // 光标移动到图片位置
                [self positionAtIndex:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection]];
                [self postHandleAddImageNode:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection]];
            }
        }
        
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        
        BOOL isPre = NO;
        BOOL isPost = NO;
        [((MMRichImageCell*)cell) getPreFlag:&isPre postFlag:&isPost];
        if (isPre) {
            [self addImageNodeAtIndexPath:_activeIndexPath image:image];
            [self postHandleAddImageNode:_activeIndexPath];
        } else if (isPost) {
            NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:_activeIndexPath.row + 1 inSection:_activeIndexPath.section];
            [self addImageNodeAtIndexPath:nextIndexPath image:image];
            [self postHandleAddImageNode:nextIndexPath];
        } else {
            NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:_activeIndexPath.row + 1 inSection:_activeIndexPath.section];
            [self addImageNodeAtIndexPath:nextIndexPath image:image];
            [self postHandleAddImageNode:nextIndexPath];
        }
        
    } else {
        MMRichImageModel* imageModel = [MMRichImageModel new];
        imageModel.image = image;
        [_datas addObject:imageModel];
        [self.tableView reloadData];
    }
}

// 处理重新加载
- (void)handleReloadItemAdIndexPath:(NSIndexPath*)indexPath {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction * deleteAction = [UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        if (indexPath.row == 0 && self->_datas.count == 1) {
            // 第一行，并且只有一个元素：添加Text
            [self deleteItemAtIndexPath:indexPath shouldPositionPrevious:NO];
            [self addTextNodeAtIndexPath:indexPath textContent:nil];
        } else {
            [self deleteItemAtIndexPath:indexPath shouldPositionPrevious:YES];
        }
    }];
    
    UIAlertAction * uploadAgainAction = [UIAlertAction actionWithTitle:@"重新上传" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        if (indexPath.row < self->_datas.count) {
            MMRichImageModel* imageModel = self->_datas[indexPath.row];
            imageModel.uploadProgress = 0;
            imageModel.isFailed = NO;
            imageModel.isDone = NO;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            // 添加到上传队列中
            [[MMFileUploadUtil sharedInstance] addUploadItem:imageModel];
        }
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:deleteAction];
    [alertController addAction:uploadAgainAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark backbtntap

- (void)backButtonTapped {
    if (self.from == ResourceFrom_FaBu) {
        if (_titleModel.textContent.length == 0) {
            NSInteger textCount = 0;
            for (int i = 0; i< _datas.count; i++) {
                NSObject* content = _datas[i];
                if ([content isKindOfClass:[MMRichTextModel class]]) {
                    MMRichTextModel* textContent = (MMRichTextModel*)content;
                    textCount += [textContent.textContent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length;
                    if (textCount == 0) {
                        [[AppDelegate sharedAppDelegate] popViewController];
                        return;
                    }
                }
            }
        }
    }
    
    if (self.articleId) {
        [[AppDelegate sharedAppDelegate] popViewController];
        return;
    }
    
    if (_haveFaBu) {
        
        [[AppDelegate sharedAppDelegate] popViewController];

    }else{
        [LEEAlert alert].config
        .LeeHeaderColor([UIColor whiteColor])
        .LeeAddContent(^(UILabel *label) {
            label.font = [UIFont systemFontOfSize:18];
            label.textColor = [UIColor blackColor];
            label.text = @"您还没有发布，是否保存到草稿箱";
        }).LeeAddAction(^(LEEAction *action) {
            action.titleColor = RGBOF(0x666666);
            action.borderColor = RGBOF(0xE0DFDF);
            action.title = @"取消";
            action.clickBlock = ^{
                [[AppDelegate sharedAppDelegate] popViewController];
            };
        })
        .LeeAddAction(^(LEEAction *action) {
            action.titleColor = RGBOF(0xF43636);
            action.borderColor = RGBOF(0xE0DFDF);
            action.title = @"确定";
            action.clickBlock = ^{
                NSMutableString *muStr = [NSMutableString string];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (id model in self.datas) {
                    if ([model isKindOfClass:[MMRichTextModel class]]) {
                        MMRichTextModel *text = (MMRichTextModel *)model;
                        NSLog(@"text.textContent - %@", text.textContent);
                        if (![NSString stringIsNull:text.textContent]) {
                            [muStr appendString:text.textContent];
                            [muArr addObject:text.textContent];
                        }
                        
                    }
                    if ([model isKindOfClass:[MMRichImageModel class]]) {
                        MMRichImageModel *text = (MMRichImageModel *)model;
                        NSLog(@"text.remoteImageUrlString - %@", text.remoteImageUrlString);
                        [muStr appendString:[NSString stringWithFormat:@"<img/>%@",text.remoteImageUrlString]];
                        [muArr addObject:text.remoteImageUrlString];
                    }
                }
                [self add_CaoGaoWithTitle:self->_titleModel.textContent TempContent:muStr contents:muArr status:@"4"];
            };
        })
        .LeeShow();
        
    }
}


#pragma mark - ......::::::: ui actoin :::::::......

- (void)RighttouchEvent {
    [self.view endEditing:YES];
//    if (_isOnUploading) {
//        return;
//    }
    
    // 验证输入
    // 1、验证内容
    if (![MMRichContentUtil validataContentNotEmptyWithRichContents:_datas]) {
        [self.view makeToast:@"文章正文不能小于20个字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 2、验证title
    if (![MMRichContentUtil validateTitle:_titleModel]) {
        [self.view makeToast:@"文章标题不能为空" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    if (_titleModel.textContent.length < 3) {
        [self.view makeToast:@"文章标题不能小于3个字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 3、验证内容是否超过上限
    if (![MMRichContentUtil validataContentNotOverflowWithRichContents:_datas]) {
        [self.view makeToast:@"文章正文不能大于500字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 4、验证图片时候上传成功
    if (![MMRichContentUtil validateImagesWithRichContents:self.datas]) {
        // 还有图片没上传或者图片失败的情况
        return;
    }
    
    // 发送内容
    _isOnUploading = YES;
    NSMutableString *muStr = [NSMutableString string];
    NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
    for (id model in self.datas) {
        if ([model isKindOfClass:[MMRichTextModel class]]) {
            MMRichTextModel *text = (MMRichTextModel *)model;
            NSLog(@"text.textContent - %@", text.textContent);
            if (![NSString stringIsNull:text.textContent]) {
                [muStr appendString:text.textContent];
                [muArr addObject:text.textContent];
            }
            
        }
        if ([model isKindOfClass:[MMRichImageModel class]]) {
            MMRichImageModel *text = (MMRichImageModel *)model;
            NSLog(@"text.remoteImageUrlString - %@", text.remoteImageUrlString);
            NSString *img = [NSString stringWithFormat:@"<img src=%@>",text.remoteImageUrlString];
            [muStr appendString:img];
            [muArr addObject:img];
        }
    }
    [self add_articleWithTitle:_titleModel.textContent TempContent:muStr contents:muArr];
}

#pragma mark - 上传
- (void)add_articleWithTitle:(NSString *)title TempContent:(NSString *)tempContent contents:(NSArray *)contents{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"article"];
    NSNumber *category = @120;
    NSNumber *subCategory = @141;

    if (_selBigCateModel) {
        category = _selBigCateModel.catid;
    }
    if (_selSmallCateModel) {
        subCategory = _selSmallCateModel.catid;
    }
    NSDictionary *param = @{};
    if (self.articleId) {
        param = @{@"title":title, @"tempContent":tempContent, @"contents":contents, @"category":category, @"subCategory":subCategory, @"source":@6, @"id":self.detailModel.ID};

    }else{
        param = @{@"title":title, @"tempContent":tempContent, @"contents":contents, @"category":category, @"subCategory":subCategory, @"source":@6};
    }
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"发布文章 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_haveFaBu = YES;
                [[UIApplication sharedApplication].keyWindow makeToast:@"发布成功，审核中" duration:1.5 position:CSToastPositionCenter];
                [[AppDelegate sharedAppDelegate] popViewController];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
    
}

#pragma mark - 保存草稿箱
- (void)add_CaoGaoWithTitle:(NSString *)title TempContent:(NSString *)tempContent contents:(NSArray *)contents status:(NSString *)status{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"article"];
    NSNumber *category = @120;
    NSNumber *subCategory = @141;
    
    if (_selBigCateModel) {
        category = _selBigCateModel.catid;
    }
    if (_selSmallCateModel) {
        subCategory = _selSmallCateModel.catid;
    }
    NSDictionary *param = @{};
    if (self.articleId) {
        param = @{@"title":title, @"tempContent":tempContent, @"contents":contents, @"category":category, @"subCategory":subCategory, @"source":@6, @"id":self.detailModel.ID};
    }else{
        param = @{@"title":title, @"tempContent":tempContent, @"contents":contents, @"category":category, @"subCategory":subCategory, @"source":@6, @"status":status};
    }
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"保存草稿箱 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_haveFaBu = YES;
                [[UIApplication sharedApplication].keyWindow makeToast:@"存入草稿箱成功" duration:1.5 position:CSToastPositionCenter];
                [[AppDelegate sharedAppDelegate] popViewController];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
    
}

- (void)onTableViewTap {
    NSIndexPath* lastIndexPath = [NSIndexPath indexPathForRow:_datas.count - 1 inSection:1];
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        [((MMRichTextCell*)cell) mm_beginEditing];
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        [((MMRichImageCell*)cell) mm_beginEditing];
    }
}


#pragma mark - Node Handler

- (void)addImageNodeAtIndexPath:(NSIndexPath*)indexPath image:(UIImage*)image {
    
    NSLog(@"addImageNodeAtIndexPath ===== %@", indexPath);
    
    UIImage* scaledImage = [MMRichContentUtil scaleImage:image];
    NSString* scaledImageStoreName= [MMRichContentUtil saveImageToLocal:scaledImage];
    if (scaledImageStoreName == nil || scaledImageStoreName.length <= 0) {
        // 提示出错
        return;
    }
    MMRichImageModel* imageModel = [MMRichImageModel new];
    imageModel.image = scaledImage;
    imageModel.localImageName = scaledImageStoreName;
    CGFloat width = [MMRichTextConfig sharedInstance].editAreaWidth;
    NSAttributedString* imgAttrStr = [imageModel attrStringWithContainerWidth:width];
    imageModel.imageContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:imgAttrStr minHeight:MMEditConfig.minImageContentCellHeight];
    
    // 添加到上传队列中
    [[MMFileUploadUtil sharedInstance] addUploadItem:imageModel];
    
    [self.tableView beginUpdates];
    [_datas insertObject:imageModel atIndex:indexPath.row];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
}

- (void)postHandleAddImageNode:(NSIndexPath*)indexPath {
    if (indexPath.row < _datas.count - 1) {
        NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        id nextData = _datas[nextIndexPath.row];
        if ([nextData isKindOfClass:[MMRichTextModel class]]) {
            // Image节点-后面：下面是text，光标移动到下面一行，并且在最前面添加一个换行，定位光标在最前面
            [self.tableView scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            MMRichTextModel* textModel = ((MMRichTextModel*)nextData);
            textModel.selectedRange = NSMakeRange(0, 0);
            textModel.shouldUpdateSelectedRange = YES;
            [self positionAtIndex:nextIndexPath];
            
        } else if ([nextData isKindOfClass:[MMRichImageModel class]]) {
            // 添加文字到下一行
            [self addTextNodeAtIndexPath:nextIndexPath textContent:@""];
        }
    } else {
        // 添加文字到下一行
        NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        [self addTextNodeAtIndexPath:nextIndexPath textContent:@""];
    }
}

- (void)addTextNodeAtIndexPath:(NSIndexPath*)indexPath textContent:(NSString*)textContent {
    MMRichTextModel* textModel = [MMRichTextModel new];
    textModel.textContent = [textContent isEqualToString:@"\n"] ? @"" : textContent == nil ? @"" : textContent;
    textModel.textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:textModel.textContent];
    
    [self.tableView beginUpdates];
    [_datas insertObject:textModel atIndex:indexPath.row];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    [self.tableView endUpdates];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    
    // 定位到新增的元素
    [self positionAtIndex:indexPath];
}

- (void)deleteItemAtIndexPathes:(NSArray<NSIndexPath*>*)actionIndexPathes shouldPositionPrevious:(BOOL)shouldPositionPrevious {
    if (actionIndexPathes.count > 0) {
        // 处理删除
        for (NSInteger i = actionIndexPathes.count - 1; i >= 0; i--) {
            NSIndexPath* actionIndexPath = actionIndexPathes[i];
            id obj = _datas[actionIndexPath.row];
            if ([obj isKindOfClass:[MMRichImageModel class]]) {
                [MMDraftUtil deleteImageContent:(MMRichImageModel*)obj];
            }
            [_datas removeObjectAtIndex:actionIndexPath.row];
        }
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:actionIndexPathes withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
        
        //  定位动到上一行
        if (shouldPositionPrevious) {
            [self positionToPreItemAtIndexPath:actionIndexPathes.firstObject];
        }
    }
}

- (void)deleteItemAtIndexPath:(NSIndexPath*)actionIndexPath shouldPositionPrevious:(BOOL)shouldPositionPrevious {
    //  定位动到上一行
    if (shouldPositionPrevious) {
        [self positionToPreItemAtIndexPath:actionIndexPath];
    }
    
    // 处理删除
    [_datas removeObjectAtIndex:actionIndexPath.row];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:actionIndexPath.row inSection:actionIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
}

/**
 定位到指定的元素
 */
- (void)positionAtIndex:(NSIndexPath*)indexPath {
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        [((MMRichTextCell*)cell) mm_beginEditing];
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        [((MMRichImageCell*)cell) mm_beginEditing];
    }
}

// 定位动到上一行
- (void)positionToPreItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    NSIndexPath* preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row - 1 inSection:actionIndexPath.section];
    [self positionAtIndex:preIndexPath];
}

// 定位动到上一行
- (void)positionToNextItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    NSIndexPath* preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row + 1 inSection:actionIndexPath.section];
    [self positionAtIndex:preIndexPath];
}

#pragma mark - ......::::::: RichTextEditDelegate :::::::......

- (void)mm_preInsertTextLineAtIndexPath:(NSIndexPath*)actionIndexPath textContent:(NSString*)textContent {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        NSIndexPath* preIndexPath = nil;
        if (actionIndexPath.row > 0) {
            preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row - 1 inSection:actionIndexPath.section];
            
            id preData = _datas[preIndexPath.row];
            if ([preData isKindOfClass:[MMRichTextModel class]]) {
                // Image节点-前面：上面是text，光标移动到上面一行，并且在最后添加一个换行，定位光标在最后将
                [self.tableView scrollToRowAtIndexPath:preIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
                
                // 设置为编辑模式
                UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:preIndexPath];
                if ([cell isKindOfClass:[MMRichTextCell class]]) {
                    [((MMRichTextCell*)cell) mm_beginEditing];
                } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
                    [((MMRichImageCell*)cell) mm_beginEditing];
                }
            } else if ([preData isKindOfClass:[MMRichImageModel class]]) {
                // Image节点-前面：上面是图片或者空，在上面添加一个Text节点，光标移动到上面一行，
                [self addTextNodeAtIndexPath:actionIndexPath textContent:textContent];
            }
            
        } else {
            // 上面为空，添加一个新的单元格
            [self addTextNodeAtIndexPath:actionIndexPath textContent:textContent];
        }
    }
}

- (void)mm_postInsertTextLineAtIndexPath:(NSIndexPath*)actionIndexPath textContent:(NSString *)textContent {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        NSIndexPath* nextIndexPath = nil;
        nextIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row + 1 inSection:actionIndexPath.section];
        if (actionIndexPath.row < _datas.count-1) {
            
            id nextData = _datas[nextIndexPath.row];
            if ([nextData isKindOfClass:[MMRichTextModel class]]) {
                // Image节点-后面：下面是text，光标移动到下面一行，并且在最前面添加一个换行，定位光标在最前面
                [self.tableView scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
                
                // 添加文字到下一行
                MMRichTextModel* textModel = ((MMRichTextModel*)nextData);
                textModel.textContent = [NSString stringWithFormat:@"%@%@", textContent, textModel.textContent];
                textModel.textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:textModel.textContent];
                if ([textContent isEqualToString:@"\n"]) {
                    textModel.selectedRange = NSMakeRange(0, 0);
                } else {
                    textModel.selectedRange = NSMakeRange(textContent.length, 0);
                }
                textModel.shouldUpdateSelectedRange = YES;
                
                // 设置为编辑模式
                UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:nextIndexPath];
                if ([cell isKindOfClass:[MMRichTextCell class]]) {
                    [((MMRichTextCell*)cell) mm_beginEditing];
                } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
                    [((MMRichImageCell*)cell) mm_beginEditing];
                }
            } else if ([nextData isKindOfClass:[MMRichImageModel class]]) {
                // Image节点-后面：下面是图片或者空，在下面添加一个Text节点，光标移动到下面一行
                [self addTextNodeAtIndexPath:nextIndexPath textContent:textContent];
            }
            
        } else {
            // Image节点-后面：下面是图片或者空，在下面添加一个Text节点，光标移动到下面一行
            [self addTextNodeAtIndexPath:nextIndexPath textContent:textContent];
        }
    }
}

- (void)mm_preDeleteItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 处理Text节点
        if (actionIndexPath.row < _datas.count) {
            
            if (actionIndexPath.row <= 0) {
                MMRichTextModel* textModel = (MMRichTextModel*)_datas[actionIndexPath.row];
                if (_datas.count == 1) {
                    // Text节点-当前的Text为空-前面-没有其他元素-：不处理
                    // Text节点-当前的Text不为空-前面-没有其他元素-：不处理
                } else {
                    if (textModel.textContent.length == 0) {
                        // Text节点-当前的Text为空-前面-有其他元素-：删除这一行，定位光标到下面图片的最后
                        [self positionToNextItemAtIndexPath:actionIndexPath];
                        [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:NO];
                    } else {
                        // Text节点-当前的Text不为空-前面-有其他元素-：不处理
                    }
                }
            } else {
                MMRichTextModel* textModel = (MMRichTextModel*)_datas[actionIndexPath.row];
                if (textModel.textContent.length == 0) {
                    // Text节点-当前的Text为空-前面-有其他元素-：删除这一行，定位光标到上面图片的最后
                    [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:YES];
                    
                } else {
                    // 当前节点不为空
                    // Text节点-当前的Text不为空-前面-：上面是图片，定位光标到上面图片的最后
                    // Text节点不存在相邻的情况，所以直接定位上上一个元素即可
                    [self positionToPreItemAtIndexPath:actionIndexPath];
                }
            }
        }
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        // 处理Image节点
        if (actionIndexPath.row < _datas.count) {
            if (actionIndexPath.row <= 0) {
                // Image节点-前面-上面为空：不处理
                // 第一行不处理
            } else {
                NSIndexPath* preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row - 1 inSection:actionIndexPath.section];
                if (preIndexPath.row < _datas.count) {
                    id preData = _datas[preIndexPath.row];
                    if ([preData isKindOfClass:[MMRichTextModel class]]) {
                        if (((MMRichTextModel*)preData).textContent.length == 0) {
                            // mage节点-前面-上面为Text（为空）：删除上面Text节点
                            [self deleteItemAtIndexPath:preIndexPath shouldPositionPrevious:NO];
                        } else {
                            [self positionToPreItemAtIndexPath:actionIndexPath];
                        }
                    } else if ([preData isKindOfClass:[MMRichImageModel class]]) {
                        [self positionToPreItemAtIndexPath:actionIndexPath];
                    }
                }
            }
        }
    }
}

- (void)mm_PostDeleteItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
        // Text节点-当前的Text不为空-后面-：正常删除
        // Text节点-当前的Text为空-后面-：正常删除，和第三种情况：为空的情况处理一样
    } else if ([cell isKindOfClass:[MMRichImageCell class]]) {
        // 处理Image节点
        if (actionIndexPath.row < _datas.count) {
            // 处理第一个节点
            if (actionIndexPath.row <= 0) {
                if (_datas.count > 1) {
                    // Image节点-后面-上面为空-列表多于一个元素：删除当前节点，光标放在后面元素之前
                    [self positionToNextItemAtIndexPath:actionIndexPath];
                    [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:NO];
                } else {
                    // Image节点-后面-上面为空-列表只有一个元素：添加一个Text节点，删除当前Image节点，光标放在添加的Text节点上
                    [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:NO];
                    [self addTextNodeAtIndexPath:actionIndexPath textContent:nil];
                }
            } else {
                // 处理非第一个节点
                NSIndexPath* preIndexPath = nil;
                if (actionIndexPath.row > 0) {
                    preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row - 1 inSection:actionIndexPath.section];
                    id preData = _datas[preIndexPath.row];
                    if ([preData isKindOfClass:[MMRichTextModel class]]) {
                        NSIndexPath* nextIndexPath = nil;
                        if (actionIndexPath.row < _datas.count - 1) {
                            nextIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row + 1 inSection:actionIndexPath.section];
                        }
                        if (nextIndexPath) {
                            id nextData = _datas[nextIndexPath.row];
                            if ([nextData isKindOfClass:[MMRichTextModel class]]) {
                                // Image节点-后面-上面为Text-下面为Text：删除Image节点，合并下面的Text到上面，删除下面Text节点，定位到上面元素的后面
                                ((MMRichTextModel*)preData).textContent = [NSString stringWithFormat:@"%@\n%@", ((MMRichTextModel*)preData).textContent, ((MMRichTextModel*)nextData).textContent];
                                ((MMRichTextModel*)preData).textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:((MMRichTextModel*)preData).textContent];
                                ((MMRichTextModel*)preData).selectedRange = NSMakeRange(((MMRichTextModel*)preData).textContent.length, 0);
                                ((MMRichTextModel*)preData).shouldUpdateSelectedRange = YES;
                                
                                [self deleteItemAtIndexPathes:@[actionIndexPath, nextIndexPath] shouldPositionPrevious:YES];
                            } else {
                                // Image节点-后面-上面为Text-下面为图片或者空：删除Image节点，定位到上面元素的后面
                                [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:YES];
                            }
                        } else {
                            // Image节点-后面-上面为Text-下面为图片或者空：删除Image节点，定位到上面元素的后面
                            [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:YES];
                        }
                        
                    } else if ([preData isKindOfClass:[MMRichImageModel class]]) {
                        // Image节点-后面-上面为图片：删除Image节点，定位到上面元素的后面
                        [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:YES];
                    }
                }
            }
        }
    }
}

// 更新ActionIndexpath
- (void)mm_updateActiveIndexPath:(NSIndexPath*)activeIndexPath {
    _activeIndexPath = activeIndexPath;
    NSLog(@"mm_updateActiveIndexPath ===== %@", activeIndexPath);
}

// 重新加载
- (void)mm_reloadItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    [self handleReloadItemAdIndexPath:actionIndexPath];
}

- (void)mm_uploadFailedAtIndexPath:(NSIndexPath *)actionIndexPath {
}

- (void)mm_uploadDonedAtIndexPath:(NSIndexPath *)actionIndexPath {
}

- (MMRichEditAccessoryView *)mm_inputAccessoryView1 {
    return [self contentInputAccessoryView];
}

- (void)mm_shouldShowAccessoryView:(BOOL)shouldShow {
    _shouldShowAccessoryView = shouldShow;
}

- (BOOL)mm_shouldCellShowPlaceholder {
    return [MMRichContentUtil shouldShowPlaceHolderFromRichContents:_datas];
}


#pragma mark - ......::::::: MMRichEditAccessoryViewDelegate :::::::......

- (void)mm_didKeyboardTapInaccessoryView:(MMRichEditAccessoryView *)accessoryView {
    [self.view endEditing:YES];
}

- (void)mm_didImageTapInaccessoryView:(MMRichEditAccessoryView *)accessoryView {
    [self handleSelectPics];
}


#pragma mark - ......::::::: Notification :::::::......

- (void)keyboardWillChangeFrame:(NSNotification*)noti {
    
    CGRect keyboardFrame = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    NSTimeInterval keyboardAnimTime = [noti.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    CGFloat keyboardH = kScreenHeight - keyboardFrame.origin.y;
    if (keyboardH > 50) {
        // 处理显示AccessorityView
        [UIView animateWithDuration:keyboardAnimTime animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, bottomOffsetHeight + contentInputAccessoryViewHeight, 0);
//            [self.contentInputAccessoryView setHiddenActionButtons:!self->_shouldShowAccessoryView];
            [self.contentInputAccessoryView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.view).offset(-(keyboardH));
                make.height.equalTo(@(contentInputAccessoryViewHeight));
                make.left.right.equalTo(self.view);
            }];
            [self.view layoutIfNeeded];
        }];
    } else {
        // 处理隐藏AccessorityView
        [UIView animateWithDuration:keyboardAnimTime animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, bottomOffsetHeight, 0);
//            [self.contentInputAccessoryView setHiddenActionButtons:!self->_shouldShowAccessoryView];
            [self.contentInputAccessoryView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.view).offset(contentInputAccessoryViewHeight);
                make.height.equalTo(@(contentInputAccessoryViewHeight));
                make.left.right.equalTo(self.view);
            }];
            [self.view layoutIfNeeded];
        }];
    }
    [UIView animateWithDuration:keyboardAnimTime animations:^{
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-keyboardH);
        }];
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - ......::::::: UITableView Handler :::::::......

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Title
    if (section == 0) {
        return 1;
    }
    // Content
    return _datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return _titleModel.cellHeight;
    } else if (indexPath.section == 1) {
        id obj = _datas[indexPath.row];
        if ([obj isKindOfClass:[MMRichTextModel class]]) {
            MMRichTextModel* textModel = (MMRichTextModel*)obj;
            return textModel.textContentHeight;
        } else if ([obj isKindOfClass:[MMRichImageModel class]]) {
            MMRichImageModel* imageModel = (MMRichImageModel*)obj;
            return imageModel.imageContentHeight;
        }
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Title
    if (indexPath.section == 0) {
        MMRichTitleCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MMRichTitleCell.class)];
        cell.delegate = self;
        [cell updateWithData:_titleModel indexPath:indexPath];
        return cell;
    }
    // Content
    id obj = _datas[indexPath.row];
    if ([obj isKindOfClass:[MMRichTextModel class]]) {
        MMRichTextCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MMRichTextCell.class)];
        cell.delegate = self;
        [cell updateWithData:obj indexPath:indexPath];
        return cell;
    }
    if ([obj isKindOfClass:[MMRichImageModel class]]) {
        MMRichImageCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MMRichImageCell.class)];
        cell.delegate = self;
        [cell updateWithData:obj];
        return cell;
    }
    
    static NSString* cellID = @"cellId";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark - 获取文章详情
- (void)getDetail{
    NSString *url = [NSString stringWithFormat:@"%@%@/%@",User_HOST, @"article",self.articleId];
//    NSDictionary *param = @{@"id":self.articleId, @"type":@"7"};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取文章详情 ---- %@",responseResult);
        
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    self.detailModel = [CYProjectModel mj_objectWithKeyValues:data];
                    self.resultDic = data;
                    if (data[@"title"]) {
                        self.titleModel.textContent = data[@"title"];
                    }else{
                        self.titleModel = [MMRichTitleModel new];
                    }
                    [self.tableView reloadData];
                    [self machiningDataWithDic:data];
                }
            }else{
                [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)initCate{
    for (CYCategrayModel *bigCate in self.categaryArr) {
        if ([bigCate.catid integerValue] == [self.detailModel.category integerValue]) {
            _selBigCateModel = bigCate;
            for (CYCategrayModel *smallCate in bigCate.child) {
                if ([smallCate.catid integerValue] == [self.detailModel.subCategory integerValue]){
                    _selSmallCateModel = smallCate;
                }
            }
        }
    }
    if (_selBigCateModel) {
        if (_selSmallCateModel) {
            [_labelBtn setTitle:[NSString stringWithFormat:@"%@-%@",_selBigCateModel.catname, _selSmallCateModel.catname] forState:UIControlStateNormal];
        }else{
            [_labelBtn setTitle:[NSString stringWithFormat:@"%@",_selBigCateModel.catname] forState:UIControlStateNormal];
        }
        [self.view layoutIfNeeded];
        [self addDelBtn];
    }else{
        [_labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    }
}

#pragma mark - 获取文章详情后 对返回数据加工处理
- (void)machiningDataWithDic:(NSDictionary *)dic{
    if (dic.count > 0) {
        NSArray * arr = [self filterTheImgUrlArrFromfahterHtml:dic[@"tempContent"]];
        _datas = [NSMutableArray array];
        if (arr.count > 0) {
            NSLog(@"arr --- %@",arr);
            for (NSString *str in arr) {
                if ([str hasSuffix:@".jpg"] || [str hasSuffix:@".png"] || [str hasSuffix:@".jpeg"]) {
                    NSString *image = str;
                    MMRichImageModel* imageModel = [MMRichImageModel new];
                    //                imageModel.localImageName = image;
                    imageModel.remoteImageUrlString = image;
                    //                imageModel.isDone = YES;
                    //                imageModel.isFailed = NO;
                    //                imageModel.imageContentHeight = 0;
                    [_datas addObject:imageModel];
                    [self downloadImageWithUrl:image];
                }else if ([str hasPrefix:@"<img>"]){
                    
                }else{
                    MMRichTextModel *text = [MMRichTextModel new];
                    text.textContent = str;
                    text.textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:str];
                    text.selectedRange = NSMakeRange(str.length, 0);
                    text.shouldUpdateSelectedRange = YES;
                    [_datas addObject:text];
                }
            }
        }else{
            _datas = [NSMutableArray array];
            [_datas addObject:[MMRichTextModel new]];
        }

    }
    if (self.categaryArr.count > 0) {
        [self initCate];
    }
}

#pragma mark - 如果包含图片 则下载图片
- (void)downloadImageWithUrl:(NSString *)url{
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager loadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        NSLog(@"imageURL -- %@",imageURL);
        for (id obj in self.datas) {
            if ([obj isKindOfClass:[MMRichImageModel class]]) {
                MMRichImageModel *imageModel = (MMRichImageModel *)obj;
                if ([imageModel.remoteImageUrlString isEqualToString:[imageURL absoluteString]]) {
                    if (!error) {
                        UIImage* scaledImage = [MMRichContentUtil scaleImage:image];
                        imageModel.image = scaledImage;
                        CGFloat width = [MMRichTextConfig sharedInstance].editAreaWidth;
                        NSAttributedString* imgAttrStr = [imageModel attrStringWithContainerWidth:width];
                        imageModel.imageContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:imgAttrStr minHeight:MMEditConfig.minImageContentCellHeight];
                    }else{
                        UIImage *imageValue = [UIImage imageWithColor:RGBOF(0xededed) Size:CGSizeMake(kWindowW, 100)];
                        imageModel.image = imageValue;
                        CGFloat width = [MMRichTextConfig sharedInstance].editAreaWidth;
                        NSAttributedString* imgAttrStr = [imageModel attrStringWithContainerWidth:width];
                        imageModel.imageContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:imgAttrStr minHeight:MMEditConfig.minImageContentCellHeight];
                    }
                }
            }
        }
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            NSInteger modelCount = 0;
            NSInteger midelImageCount = 0;
            for (id obj in self.datas) {
                if ([obj isKindOfClass:[MMRichImageModel class]]) {
                    MMRichImageModel *imageModel = (MMRichImageModel *)obj;
                    modelCount += 1;
                    if (imageModel.image) {
                        midelImageCount += 1;
                    }
                }
            }
            if (modelCount == midelImageCount) {
                [self.tableView reloadData];
            }
        });
    }];
}

- (NSArray *)filterTheImgUrlArrFromfahterHtml:(NSString *)html{
    ///<img|IMG)[^\<\>]*>找img标签的正则
    //    NSString *ss = @"<(img|IMG)[^\\<\\>]*>";//img标签的正则表达式
    NSString *ss = @"<img\\b.*?(?:\\>|\\/>)";//img标签的正则表达式
    //    NSString *ss = @"/\"([^\"]*)\"/";//img标签的正则表达式
    NSString *subHtml = html;
    NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
    while (subHtml.length != 0) {
        NSRegularExpression *pre = [[NSRegularExpression alloc] initWithPattern:ss options:0 error:nil];
        NSArray *arr = [pre matchesInString:subHtml options:NSMatchingReportProgress range:NSMakeRange(0, subHtml.length)];//这个方法匹配正则，找到符合的结果返回数组集合，返回的类型是NSTextCheckingResult下面会提到。
        NSLog(@"arr - %@",arr);
        if (arr.count > 0) {
            NSTextCheckingResult *match = [arr firstObject];
            NSRange matchRange = [match range];//返回的是每个imgb标签的位置
            //截取文本
            NSString *title = [subHtml substringWithRange:NSMakeRange(0, matchRange.location)];
            [muArr addObject:title];
            
            NSString *imgDivStr = [html substringWithRange:matchRange];//根据位置找对应img标签
            
            imgDivStr = [imgDivStr stringByReplacingOccurrencesOfString:@" " withString:@""];
            //此处我为了找出图片URL过滤掉空格
            
            NSString *imgUrl = [[imgDivStr componentsSeparatedByString:@"src=\""] lastObject];
            imgUrl = [[imgUrl componentsSeparatedByString:@"\""] firstObject];
            NSString *imgstr = [NSString stringWithFormat:@"<img>%@",imgUrl];
            [muArr addObject:imgstr];
            subHtml = [NSMutableString stringWithString:[subHtml substringWithRange:NSMakeRange(matchRange.location + matchRange.length, subHtml.length - matchRange.location - matchRange.length)]];
        }else{
            //截取文本
            NSString *title = [subHtml substringWithRange:NSMakeRange(0, subHtml.length)];
            [muArr addObject:title];
            subHtml = @"";
        }
    }
    return [NSArray arrayWithArray:muArr];
}


#pragma mark - 获取所有分类
- (void)getAllCategary{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"categories"];
    NSDictionary *param = @{@"type":@7};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取所有分类 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *data = responseResult[@"data"];
                    [self.categaryArr removeAllObjects];
                    for (NSDictionary *dic in data) {
                        NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                        [muDic setObject:dic[@"name"] forKey:@"catname"];
                        [muDic setObject:dic[@"id"] forKey:@"catid"];
                        [muDic setObject:dic[@"childCates"] forKey:@"child"];
                        [muDic removeObjectForKey:@"id"];
                        [muDic removeObjectForKey:@"name"];
                        [muDic removeObjectForKey:@"childCates"];

                        CYCategrayModel *model = [CYCategrayModel modelWithDictionary:muDic];
                        [self.categaryArr addObject:model];
                    }
                    if (self.detailModel) {
                        [self initCate];
                    }
                }
            }else{
                
            }
        }
    }];
}

#pragma mark - 底部选择标签视图
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 115)];
        _bottomView.backgroundColor = BackGroundColor;
        
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.top.equalTo(self->_bottomView).with.mas_equalTo(15);
            make.right.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.height.mas_equalTo(100);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        [view addSubview:label];
        label.text = @"选择行业";
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = RGBOF(0x666666);
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).with.mas_equalTo(15);
            make.top.equalTo(view).with.mas_equalTo(15);
            make.right.equalTo(view).with.mas_equalTo(-15);

        }];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _labelBtn = btn;
        [btn setTitle:@"+ 添加" forState:UIControlStateNormal];
        [btn setTitleColor:RGBOF(0x97A2B9) forState:UIControlStateNormal];
        [btn setBackgroundColor:RGBOF(0xF4F5FA)];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 25)];
        btn.layer.cornerRadius = 15;
        btn.layer.masksToBounds = YES;
//        btn.layer.borderWidth = 1;
//        btn.layer.borderColor = RGBOF(0xe3e3e3).CGColor;
        [view addSubview:btn];
        [btn addTarget:self action:@selector(showlabel:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).with.mas_equalTo(15);
            make.top.equalTo(label.mas_bottom).with.mas_equalTo(15);
            make.height.mas_equalTo(30);
        }];
    }
    return _bottomView;
}


- (void)showlabel:(UIButton *)sender{
 [self.view endEditing:YES];
    NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYSelCategaryView" owner:self options:nil];
    CYSelCategaryView *backView = [nibView objectAtIndex:0];
    backView.frame = CGRectMake(0, 0, kWindowW, 410);
    backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    backView.dataSourceArr = self.categaryArr;
    backView.haveSmallCategary = YES;
    __weak typeof(self)weakself = self;
    backView.block = ^(CYCategrayModel * _Nonnull bigCateModel, CYCategrayModel * _Nonnull smallCateModel) {
        self->_selBigCateModel = bigCateModel;
        self->_selSmallCateModel = smallCateModel;
        if (bigCateModel) {
            if (smallCateModel) {
                [self->_labelBtn setTitle:[NSString stringWithFormat:@"%@-%@",bigCateModel.catname, smallCateModel.catname] forState:UIControlStateNormal];
            }else{
                [self->_labelBtn setTitle:[NSString stringWithFormat:@"%@",bigCateModel.catname] forState:UIControlStateNormal];
            }
            [weakself.view layoutIfNeeded];
            [weakself addDelBtn];
        }else{
            [self->_labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
        }

    };
    [GKCover translucentCoverFrom:[UIApplication sharedApplication].keyWindow content:backView animated:YES showBlock:^{
        // 显示出来时的block
        NSLog(@"弹窗显示了，6不6");
    } hideBlock:^{
        // 移除后的block
        NSLog(@"弹窗消失了，555");
    }];
}

- (void)addDelBtn{
    for (UIView *view in self.bottomView.subviews) {
        if (view.tag == 10033) {
            [view removeFromSuperview];
        }
    }
    UIButton *btn = [[UIButton alloc] init];
    btn.tag = 10033;
    [btn setImage:[UIImage imageNamed:@"ss_gb"] forState:UIControlStateNormal];
    [self.bottomView addSubview:btn];
    [btn addTarget:self action:@selector(delCate:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat marginLeft = _labelBtn.frame.size.width + 7;
    __weak typeof(self)weakself = self;
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(14);
        make.height.mas_equalTo(14);
    make.left.equalTo(weakself.bottomView).with.mas_equalTo(marginLeft);
        make.top.equalTo(weakself.bottomView).with.mas_equalTo(60);
    }];
}

- (void)delCate:(UIButton *)sender{
    [_labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    _selBigCateModel = nil;
    _selSmallCateModel = nil;
    [sender removeFromSuperview];
}

- (HXPhotoManager *)manager
{
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.photoMaxNum = 1;
        _manager.configuration.restoreNavigationBar = YES;
        _manager.configuration.deleteTemporaryPhoto = NO;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.creationDateSort = YES;
        _manager.configuration.supportRotation = NO;
        _manager.configuration.cameraCellShowPreview = NO;
        _manager.configuration.navBarBackgroudColor = [UIColor whiteColor];
        _manager.configuration.navigationTitleColor = [UIColor blackColor];
        
        _manager.configuration.originalNormalImageName = @"zpgl_fb_wxz";
        _manager.configuration.originalSelectedImageName = @"zpgl_fb_xz";
        
        _manager.configuration.navigationBar = ^(UINavigationBar *navigationBar, UIViewController *viewController) {
            [navigationBar setBackgroundImage:[UIImage imageNamed:@"APPCityPlayer_bannerGame"] forBarMetrics:UIBarMetricsDefault];
            navigationBar.barTintColor = [UIColor whiteColor];
            navigationBar.tintColor = [UIColor blackColor];
        };
        
        __weak typeof(self) weakSelf = self;
        _manager.configuration.photoListBottomView = ^(HXDatePhotoBottomView *bottomView) {
        };
        _manager.configuration.previewBottomView = ^(HXDatePhotoPreviewBottomView *bottomView) {
        };
        _manager.configuration.albumListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"albumList:%@",collectionView);
        };
        _manager.configuration.photoListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"photoList:%@",collectionView);
        };
        _manager.configuration.previewCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"preview:%@",collectionView);
        };
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        
        // 使用自动的相机  这里拿系统相机做示例
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
        //        _manager.shouldSelectModel = ^NSString *(HXPhotoModel *model) {
        //            // 如果return nil 则会走默认的判断是否达到最大值
        //            //return nil;
        //            return @"Demo1 116 - 120 行注释掉就能选啦~\(≧▽≦)/~";
        //        };
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.photoCanEdit = YES;
    }
    return _manager;
}

- (NSMutableArray *)categaryArr{
    if (!_categaryArr) {
        _categaryArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _categaryArr;
}

@end
